import storage from '@/utils/storage';
import fs from 'react-native-fs';
import AppEnvironments from './AppEnvironment';

export default {
  async uploadFile(uri: string): Promise<string | undefined> {
    const token = storage.getString('auth_token');
    let filename = uri.split('/').pop();
    const formData = new FormData();
    formData.append('file', {
      uri: uri.replaceAll('file://', ''),
      name: filename,
      type: 'image',
    });
    return fetch(
      `${AppEnvironments.current.baseURL}/api/admin/sys-file/upload`,
      {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          // 如果需要认证
          Authorization: `Bearer ${token}`,
        },
      }
    )
      .then((res) => res.json())
      .then((value) => {
        console.log(JSON.parse(value));
        const fileName = value?.data?.fileName ?? '';
        return AppEnvironments.current.ossURL + fileName;
      })
      .catch((reaspon) => {
        console.log('报错了！', reaspon);
        return '';
      });
  },

  uploadImage(uri: string): Promise<string | undefined> {
    const token = storage.getString('auth_token');
    let filename = uri.split('/').pop() ?? '';
    return fs
      .uploadFiles({
        files: [
          {
            filename: filename,
            name: 'file',
            filepath: uri.replace('file://', ''),
            filetype: 'image',
          },
        ],
        headers: {
          Authorization: `Bearer ${token}`,
        },
        toUrl: `${AppEnvironments.current.baseURL}admin/sys-file/upload`,
      })
      .promise.then(({ body }) => {
        const { data } = JSON.parse(body);
        const imageUrl = AppEnvironments.current.ossURL + data.fileName;
        return imageUrl;
      })
      .catch((reason) => {
        console.log('图片上传失败：', reason);
        return undefined;
      });
  },
};
